<?php
if (!defined('SHARE_VERSION')) exit('No direct script access allowed');

class MenuController extends CommonController
{
	public function Index(){
		$list = $this->db->table("@_menu")->order("sort ASC, id ASC")->findAll();
		include $this->display('menu.html');
	}

	public function Update(){
		if ($_POST) {
			$id 	= getGpc('id', 'string', 'P');
			$name	= getGpc('name', 'string', 'P');
			$sort	= getGpc('sort', 'string', 'P');
			$is_use	= getGpc('is_use', 'string', 'P');
			foreach ($id as $key => $v) {
				$ids	= intval($v);
				$data['name']	= trim($name[$key]);
				$data['sort']	= intval($sort[$key]);
				$data['is_use']	= intval($is_use[$key]);
				if ($ids>0) {
					// 执行更新操作
					$this->db->table("@_menu")->where("id={$ids}")->update($data);
				} else {
					if (!empty($data['name'])) {
						$this->db->table("@_menu")->add($data);
					}
				}
			}
			$this->_cache();
			return true;
		}
	}

	public function Del(){
		$id 		= getGpc('id', 'integer', 'G');
		if (empty($id)) {
			$this->msg('参数错误。');
		}
		$this->db->table("@_menu")->where("id=$id")->delete();
		$this->_cache();
		$result['status']	= 1;
		echo json_encode($result);
	}

	// 更新缓存
	private function _cache(){
		$list     = $this->db->table("@_menu")->order("sort ASC")->findAll();
		$menu_num = count($list);
		$menu_list = array();
		foreach ($list as $key => $v) {
			$menu_list[$v['id']]	= $v['name'];
			$list[$key]['num']	= $menu_num;
			$list[$key]['node']	= $this->db->table("@_role_node")->where("menu_id={$v['id']}")->order("sort ASC, id ASC")->findAll();
		}
		$this->cache->write($list, 'menu_list');
		$this->cache->write($menu_list, 'menu_item');
	}
}
?>